"use client"

import type React from "react"

import { useState, useRef } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { AlertCircle, FileText, Upload, Info } from "lucide-react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { detectEncoding, decodeText } from "@/lib/text-encoding-polyfill"

export default function FileMerger() {
  const [files, setFiles] = useState<File[]>([])
  const [delimiter, setDelimiter] = useState("\n---\n")
  const [isProcessing, setIsProcessing] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [preview, setPreview] = useState<string>("")
  const [selectedEncoding, setSelectedEncoding] = useState<string>("auto")
  const [fileEncodings, setFileEncodings] = useState<Record<string, string>>({})
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    setError(null)
    if (!e.target.files || e.target.files.length === 0) {
      return
    }

    // if (e.target.files.length > 20) {
    //   setError("最多只能上传20个文件")
    //   return
    // }

    const fileArray = Array.from(e.target.files)
    setFiles(fileArray)

    // Generate preview of file names
    const fileNames = fileArray.map((file) => file.name).join("\n")
    setPreview(fileNames)

    // 如果是自动检测模式，尝试检测每个文件的编码
    if (selectedEncoding === "auto") {
      const newFileEncodings: Record<string, string> = {}

      for (const file of fileArray) {
        try {
          const buffer = await readFileAsArrayBuffer(file)
          const detectedEncoding = await detectEncoding(buffer)
          newFileEncodings[file.name] = detectedEncoding
        } catch (err) {
          console.error(`无法检测文件 ${file.name} 的编码:`, err)
          newFileEncodings[file.name] = "UTF-8" // 默认使用UTF-8
        }
      }

      setFileEncodings(newFileEncodings)
    }
  }

  const readFileAsArrayBuffer = (file: File): Promise<ArrayBuffer> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()

      reader.onload = (event) => {
        if (event.target?.result) {
          resolve(event.target.result as ArrayBuffer)
        } else {
          reject(new Error("读取文件失败"))
        }
      }

      reader.onerror = () => {
        reject(new Error(`读取文件 ${file.name} 失败`))
      }

      reader.readAsArrayBuffer(file)
    })
  }

  const readFileAsText = async (file: File): Promise<string> => {
    try {
      // 首先读取文件为ArrayBuffer
      const buffer = await readFileAsArrayBuffer(file)

      // 确定使用的编码
      let encodingToUse = selectedEncoding

      if (selectedEncoding === "auto") {
        // 使用之前检测到的编码或重新检测
        encodingToUse = fileEncodings[file.name] || (await detectEncoding(buffer))
      }

      // 使用确定的编码解码文本
      return await decodeText(buffer, encodingToUse)
    } catch (err) {
      console.error(`读取文件 ${file.name} 失败:`, err)
      throw new Error(`读取文件 ${file.name} 失败: ${err instanceof Error ? err.message : String(err)}`)
    }
  }

  const mergeFiles = async () => {
    if (files.length === 0) {
      setError("请至少上传一个文件")
      return
    }

    setIsProcessing(true)
    setError(null)

    try {
      const mergedContent: string[] = []

      for (const file of files) {
        const content = await readFileAsText(file)
        // 在每个文件内容的开头添加分隔符
        mergedContent.push(delimiter + content)
      }

      // 合并所有内容（不需要额外的分隔符，因为每个文件内容已经以分隔符开头）
      const result = mergedContent.join("")
      downloadMarkdown(result)
    } catch (err) {
      setError("处理文件时出错: " + (err instanceof Error ? err.message : String(err)))
    } finally {
      setIsProcessing(false)
    }
  }

  const downloadMarkdown = (content: string) => {
    const blob = new Blob([content], { type: "text/markdown;charset=utf-8" })
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = "merged_content.md"
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  const clearFiles = () => {
    setFiles([])
    setPreview("")
    setFileEncodings({})
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }

  return (
    <div className="w-full max-w-3xl space-y-6">
      <div className="space-y-2">
        <Label htmlFor="files">上传文本文件 (最多20个)</Label>
        <div className="flex items-center gap-2">
          <Input
            ref={fileInputRef}
            id="files"
            type="file"
            multiple
            accept=".txt"
            onChange={handleFileChange}
            className="flex-1"
          />
          {files.length > 0 && (
            <Button variant="outline" onClick={clearFiles}>
              清除
            </Button>
          )}
        </div>
        <p className="text-sm text-muted-foreground">支持多种编码的TXT文件，包括UTF-8、GBK、GB2312等</p>
      </div>

      {files.length > 0 && (
        <div className="space-y-2">
          <Label>已选择 {files.length} 个文件:</Label>
          <Textarea value={preview} readOnly className="h-32 font-mono text-sm" />
        </div>
      )}

      <div className="space-y-2">
        <Label htmlFor="encoding">文件编码</Label>
        <Select value={selectedEncoding} onValueChange={setSelectedEncoding}>
          <SelectTrigger id="encoding">
            <SelectValue placeholder="选择文件编码" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="auto">自动检测</SelectItem>
            <SelectItem value="UTF-8">UTF-8</SelectItem>
            <SelectItem value="GBK">GBK (简体中文)</SelectItem>
            <SelectItem value="GB2312">GB2312 (简体中文)</SelectItem>
            <SelectItem value="BIG5">BIG5 (繁体中文)</SelectItem>
            <SelectItem value="Shift_JIS">Shift_JIS (日文)</SelectItem>
            <SelectItem value="EUC-KR">EUC-KR (韩文)</SelectItem>
            <SelectItem value="ISO-8859-1">ISO-8859-1 (西欧)</SelectItem>
            <SelectItem value="windows-1252">Windows-1252 (西欧)</SelectItem>
          </SelectContent>
        </Select>
        <p className="text-sm text-muted-foreground">选择文件的编码格式，如果出现乱码，请尝试不同的编码</p>
      </div>

      <div className="space-y-2">
        <Label htmlFor="delimiter">分隔符</Label>
        <Textarea
          id="delimiter"
          value={delimiter}
          onChange={(e) => setDelimiter(e.target.value)}
          placeholder="输入用于分隔文件内容的文本"
          className="h-20"
        />
        <p className="text-sm text-muted-foreground">此文本将添加到每个文件内容的开头</p>
      </div>

      {error && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>错误</AlertTitle>
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      <Alert>
        <Info className="h-4 w-4" />
        <AlertTitle>编码提示</AlertTitle>
        <AlertDescription>
          如果合并后的文件出现乱码，请尝试选择不同的编码。中文文件常用的编码有GBK、GB2312等。
        </AlertDescription>
      </Alert>

      <div className="flex justify-center">
        <Button
          onClick={mergeFiles}
          disabled={isProcessing || files.length === 0}
          className="w-full md:w-auto"
          size="lg"
        >
          {isProcessing ? "处理中..." : "合并并下载"}
          {!isProcessing && <FileText className="ml-2 h-4 w-4" />}
        </Button>
      </div>

      <div className="bg-muted p-4 rounded-md">
        <h3 className="font-medium mb-2 flex items-center">
          <Upload className="mr-2 h-4 w-4" />
          使用说明
        </h3>
        <ol className="list-decimal list-inside space-y-1 text-sm">
          <li>上传最多20个TXT文本文件</li>
          <li>选择适当的文件编码（如果出现乱码，请尝试GBK或GB2312等中文编码）</li>
          <li>在分隔符输入框中输入您想要的分隔文本</li>
          <li>点击"合并并下载"按钮</li>
          <li>系统将在每个文件内容的开头添加分隔符，并自动下载合并后的Markdown文件</li>
        </ol>
      </div>
    </div>
  )
}
